<template>
  <div class="user-profile-container">
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 用户基本信息卡片 -->
      <el-card v-loading="loading" class="user-info-card">
        <div class="user-header">
          <div class="user-avatar-wrapper">
            <el-avatar
              :size="120"
              :src="formatAvatarUrl(userProfile?.avatar)"
              :icon="UserFilled"
              class="user-avatar"
            />
          </div>
          <div class="user-details">
            <div class="user-name">
              <h2>{{ userProfile?.nickName }}</h2>
              <el-tag
                v-if="userProfile?.sexName"
                size="small"
                :type="userProfile.sexName === '男' ? 'primary' : 'danger'"
                effect="plain"
                class="sex-tag"
              >
                {{ userProfile.sexName }}
              </el-tag>
            </div>
            <div v-if="userProfile?.signature" class="user-signature">
              <IconifyIconOffline icon="ep:edit-pen" />
              {{ userProfile.signature }}
            </div>
            <div class="user-meta">
              <span v-if="userProfile?.userName" class="meta-item">
                <IconifyIconOffline icon="ep:user" />
                @{{ userProfile.userName }}
              </span>
              <span class="meta-item">
                <IconifyIconOffline icon="ep:calendar" />
                {{ formatJoinTime(userProfile?.createTime) }}
              </span>
            </div>
            <div v-if="userProfile?.email" class="user-email">
              <IconifyIconOffline icon="ep:message" />
              {{ userProfile.email }}
            </div>
          </div>
          <!-- 操作按钮区域 -->
          <div class="user-actions">
            <!-- 当前用户：显示编辑资料按钮 -->
            <template v-if="isCurrentUser">
              <el-button
                type="primary"
                size="default"
                class="action-button edit-button"
                @click="handleEditProfile"
              >
                <el-icon><Edit /></el-icon>
                编辑资料
              </el-button>
            </template>
            <!-- 其他用户：显示关注按钮 -->
            <template v-else>
              <el-button
                :type="userProfile?.isFollowed ? 'default' : 'primary'"
                :loading="followLoading"
                class="action-button follow-button"
                @click="handleFollow"
              >
                <IconifyIconOffline
                  :icon="userProfile?.isFollowed ? 'ep:check' : 'ep:plus'"
                />
                {{ userProfile?.isFollowed ? "已关注" : "关注" }}
              </el-button>
            </template>
          </div>
        </div>
      </el-card>

      <!-- 统计数据卡片 -->
      <el-card class="stats-card">
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-value">
              {{ formatNumber(userProfile?.stats?.articleCount || 0) }}
            </div>
            <div class="stat-label">
              <IconifyIconOffline icon="ep:document" />
              文章
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-value">
              {{ formatNumber(userProfile?.stats?.totalViewCount || 0) }}
            </div>
            <div class="stat-label">
              <IconifyIconOffline icon="ep:view" />
              阅读
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-value">
              {{ formatNumber(userProfile?.stats?.totalLikeCount || 0) }}
            </div>
            <div class="stat-label">
              <IconifyIconOffline icon="ep:heart-filled" />
              点赞
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-value">
              {{ formatNumber(userProfile?.stats?.followerCount || 0) }}
            </div>
            <div class="stat-label">
              <IconifyIconOffline icon="ep:user-filled" />
              粉丝
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-value">
              {{ formatNumber(userProfile?.stats?.followingCount || 0) }}
            </div>
            <div class="stat-label">
              <IconifyIconOffline icon="ep:user" />
              关注
            </div>
          </div>
        </div>
      </el-card>

      <!-- 内容区域 -->
      <div class="content-area">
        <el-tabs v-model="activeTab" class="profile-tabs">
          <el-tab-pane name="articles">
            <template #label>
              <span class="tab-label">
                <IconifyIconOffline icon="ep:document" />
                文章
              </span>
            </template>
            <UserArticleShowcase :user-id="userId" />
          </el-tab-pane>
          <el-tab-pane name="liked">
            <template #label>
              <span class="tab-label">
                <IconifyIconOffline icon="ep:heart-filled" />
                {{ isCurrentUser ? "我的点赞" : "点赞文章" }}
              </span>
            </template>
            <LikedArticlesList
              :user-id="userId"
              :is-current-user="isCurrentUser"
            />
          </el-tab-pane>
          <el-tab-pane name="collected">
            <template #label>
              <span class="tab-label">
                <IconifyIconOffline icon="ep:star-filled" />
                {{ isCurrentUser ? "我的收藏" : "收藏文章" }}
              </span>
            </template>
            <CollectedArticlesList
              :user-id="userId"
              :is-current-user="isCurrentUser"
            />
          </el-tab-pane>
          <el-tab-pane name="following">
            <template #label>
              <span class="tab-label">
                <IconifyIconOffline icon="ep:user" />
                关注
              </span>
            </template>
            <UserFollowingList :user-id="userId" />
          </el-tab-pane>
          <el-tab-pane name="followers">
            <template #label>
              <span class="tab-label">
                <IconifyIconOffline icon="ep:user-filled" />
                粉丝
              </span>
            </template>
            <UserFollowersList :user-id="userId" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { UserFilled, Edit } from "@element-plus/icons-vue";
import { IconifyIconOffline } from "@/components/ReIcon";
import { useUserAuthStore } from "@/store/modules/userAuth";
import {
  getUserProfileApi,
  getCurrentUserProfileApi,
  followUserApi,
  formatNumber,
  formatTime,
  type UserProfile
} from "@/api/user-profile";

import UserArticleShowcase from "./components/UserArticleShowcase.vue";
import UserFollowingList from "./components/UserFollowingList.vue";
import UserFollowersList from "./components/UserFollowersList.vue";
import LikedArticlesList from "./components/LikedArticlesList.vue";
import CollectedArticlesList from "./components/CollectedArticlesList.vue";

const route = useRoute();
const router = useRouter();
const userAuthStore = useUserAuthStore();

// 响应式数据
const loading = ref(false);
const followLoading = ref(false);
const userProfile = ref<UserProfile | null>(null);
const activeTab = ref("articles");
const searchKeyword = ref("");

// 计算属性
const userId = computed(() => {
  const id = route.params.id as string;
  if (id) {
    const parsedId = parseInt(id);
    return isNaN(parsedId) ? null : parsedId;
  }
  return userAuthStore.userId || null;
});

const isCurrentUser = computed(() => {
  return userId.value === userAuthStore.userId;
});

// 方法
const loadUserProfile = async () => {
  try {
    loading.value = true;
    let response;

    if (isCurrentUser.value) {
      response = await getCurrentUserProfileApi();
    } else {
      response = await getUserProfileApi(userId.value);
    }

    if (response.code === 200) {
      userProfile.value = response.data;
    } else {
      ElMessage.error(response.message || "获取用户信息失败");
    }
  } catch (error) {
    console.error("加载用户信息失败:", error);
    ElMessage.error("获取用户信息失败");
  } finally {
    loading.value = false;
  }
};

const handleFollow = async () => {
  if (!userProfile.value) return;

  try {
    followLoading.value = true;
    const isFollow = !userProfile.value.isFollowed;

    const response = await followUserApi({
      userId: userId.value,
      isFollow
    });

    if (response.code === 200) {
      userProfile.value.isFollowed = isFollow;
      // 更新统计数据
      if (isFollow) {
        userProfile.value.stats.followerCount++;
      } else {
        userProfile.value.stats.followerCount--;
      }
      ElMessage.success(isFollow ? "关注成功" : "取消关注成功");
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("关注操作失败:", error);
    ElMessage.error("操作失败，请稍后重试");
  } finally {
    followLoading.value = false;
  }
};

const handleEditProfile = () => {
  router.push("/user/profile-edit");
};

// 格式化头像URL
const formatAvatarUrl = (url: string): string => {
  if (!url) return "";

  // 如果已经是完整URL，直接返回
  if (url.startsWith("http://") || url.startsWith("https://")) {
    return url;
  }

  // 如果是相对路径，添加基础URL
  const baseURL = import.meta.env.DEV
    ? "http://localhost:8081"
    : "http://localhost:8081";
  return baseURL + url;
};

const formatJoinTime = (timeStr?: string) => {
  if (!timeStr) return "";
  const date = new Date(timeStr);
  return `${date.getFullYear()}年${date.getMonth() + 1}月加入`;
};

// 监听userId变化(包括路由参数和当前用户)
watch(
  userId,
  (newUserId, oldUserId) => {
    if (newUserId && newUserId !== oldUserId) {
      console.log(
        `🔄 用户ID变化，重新加载用户资料: ${oldUserId} -> ${newUserId}`
      );
      // 重置activeTab
      activeTab.value = "articles";
      loadUserProfile();
    }
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped>
// 响应式设计
@media (width <= 768px) {
  .user-profile-container {
    padding: 12px;
  }

  .user-info-card {
    .user-header {
      flex-direction: column;
      gap: 16px;
      align-items: center;
      text-align: center;

      .user-avatar-wrapper {
        .user-avatar {
          width: 100px !important;
          height: 100px !important;
        }
      }

      .user-details {
        .user-name {
          flex-direction: column;
          gap: 8px;
          justify-content: center;

          h2 {
            font-size: 20px;
          }
        }

        .user-meta {
          flex-direction: column;
          gap: 8px;
          justify-content: center;
        }

        .user-email {
          justify-content: center;
        }
      }

      .user-actions {
        gap: 8px;
        align-items: stretch;
        width: 100%;

        .action-button {
          width: 100%;
          min-width: unset;
        }
      }
    }
  }

  .stats-card {
    .stats-grid {
      grid-template-columns: repeat(2, 1fr);
      gap: 0;

      .stat-item {
        padding: 16px 12px;
        border-right: 1px solid #e4e7ed;
        border-bottom: 1px solid #e4e7ed;

        &:nth-child(2n)::after {
          display: none;
        }

        &:nth-child(2n) {
          border-right: none;
        }

        &:nth-last-child(-n + 2) {
          border-bottom: none;
        }

        .stat-value {
          font-size: 22px;
        }

        .stat-label {
          font-size: 13px;
        }
      }
    }
  }

  .main-content {
    padding: 16px;
  }
}

.user-profile-container {
  min-height: 100vh;
  background: #f5f7fa;
}

// 主要内容区域
.main-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
  max-width: 1200px;
  padding: 24px 20px;
  margin: 0 auto;
}

.user-info-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  }

  :deep(.el-card__body) {
    padding: 24px;
  }

  .user-header {
    display: flex;
    gap: 24px;
    align-items: flex-start;

    .user-avatar-wrapper {
      flex-shrink: 0;

      .user-avatar {
        border: 3px solid #409eff;
        transition: all 0.3s ease;

        &:hover {
          box-shadow: 0 4px 12px rgb(64 158 255 / 30%);
          transform: scale(1.05);
        }
      }
    }

    .user-details {
      flex: 1;
      min-width: 0;

      .user-name {
        display: flex;
        gap: 12px;
        align-items: center;
        margin-bottom: 12px;

        h2 {
          margin: 0;
          font-size: 24px;
          font-weight: 600;
          color: #303133;
        }

        .sex-tag {
          font-weight: 500;
        }
      }

      .user-signature {
        display: flex;
        gap: 6px;
        align-items: center;
        padding: 8px 12px;
        margin-bottom: 12px;
        font-size: 14px;
        font-style: italic;
        color: #606266;
        background: #f5f7fa;
        border-radius: 4px;

        .iconify {
          font-size: 14px;
          color: #909399;
        }
      }

      .user-meta {
        display: flex;
        gap: 20px;
        align-items: center;
        margin-bottom: 12px;
        font-size: 14px;
        color: #606266;

        .meta-item {
          display: flex;
          gap: 6px;
          align-items: center;

          .iconify {
            font-size: 14px;
            color: #909399;
          }
        }
      }

      .user-email {
        display: flex;
        gap: 6px;
        align-items: center;
        font-size: 14px;
        color: #909399;

        .iconify {
          font-size: 14px;
        }
      }
    }

    .user-actions {
      display: flex;
      flex-shrink: 0;
      flex-direction: column;
      gap: 10px;
      align-items: flex-end;
      justify-content: flex-start;

      .action-button {
        min-width: 120px;
        transition: all 0.3s ease;

        .el-icon {
          margin-right: 6px;
        }

        &:hover {
          transform: translateY(-2px);
        }

        &:active {
          transform: translateY(0);
        }
      }
    }
  }
}

.stats-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  }

  :deep(.el-card__body) {
    padding: 20px;
  }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 0;

    .stat-item {
      position: relative;
      padding: 20px 16px;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s ease;

      &:not(:last-child)::after {
        position: absolute;
        top: 20%;
        right: 0;
        width: 1px;
        height: 60%;
        content: "";
        background: #e4e7ed;
      }

      &:hover {
        background: #f5f7fa;

        .stat-value {
          color: #409eff;
          transform: scale(1.08);
        }

        .stat-label {
          color: #409eff;
        }
      }

      .stat-value {
        margin-bottom: 8px;
        font-size: 26px;
        font-weight: 600;
        color: #303133;
        transition: all 0.3s ease;
      }

      .stat-label {
        display: flex;
        gap: 4px;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        color: #606266;
        transition: all 0.3s ease;

        .iconify {
          font-size: 14px;
        }
      }
    }
  }
}

.content-area {
  .profile-tabs {
    background: #fff;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
    }

    :deep(.el-tabs__header) {
      padding: 16px 16px 0;
      margin-bottom: 0;
    }

    :deep(.el-tabs__active-bar) {
      height: 2px;
    }

    :deep(.el-tabs__content) {
      padding: 20px 16px;
    }

    .tab-label {
      display: flex;
      gap: 6px;
      align-items: center;
      transition: all 0.3s ease;

      .iconify {
        font-size: 14px;
      }
    }

    :deep(.el-tabs__item) {
      padding: 0 16px;
      font-size: 14px;
      transition: all 0.3s ease;

      &:hover:not(.is-active) {
        color: #409eff;
      }
    }
  }
}
</style>
